package com.weipai.springboot.base.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.api.domain.UserDetails;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.model.sys.User;
import com.weipai.springboot.util.PasswordHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: gusl
 * @Date: 2019/6/14 18:06
 * @Description:
 */
public class MyAuthenticationFilter extends FormAuthenticationFilter {
    public static final String AUTH_TOKEN_HEADER = "Authentication-Token";
    public static String sessionid="";
    private static final Logger logger = LoggerFactory.getLogger(MyAuthenticationFilter.class);
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object handler) throws Exception {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest HttpServletRequest = (javax.servlet.http.HttpServletRequest) request;
        if (HttpServletRequest.getMethod().equals("OPTIONS")) {
           /* HttpServletRequest.setStatus(HttpServletResponse.SC_OK);*/
            return true;
        }
        String sessionId = httpServletResponse.getHeader((String) sessionid);
        HttpSession session1 = HttpServletRequest.getSession();
        if (HttpServletRequest.getMethod().equals("OPTIONS")) {
   /* HttpServletRequest.setStatus(HttpServletResponse.SC_OK);*/
            return true;
        }
     /*   User activeUser = ShiroUtil.getActiveUser(sessionid, HttpServletRequest, httpServletResponse);*/
        String authToken = HttpServletRequest.getHeader(AUTH_TOKEN_HEADER);
        Response ret = new Response();
        if (authToken != null&&!authToken.equals("")) {
            //app端
            boolean isValid = false;
            try {
                isValid = PasswordHelper.validateToken(authToken);
            } catch (Exception e) {
                logger.error("validate token with error = {}", e);
            }
            if (isValid) {
                //已登录


                String username = PasswordHelper.getUserName(authToken);
               /* DUser user = userService.getUserByLoginName(username);*/
                if (StringUtils.isEmpty(username)) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    result.put("code", RetCode.NOT_LOGIN.getCode());
                    result.put("msg", RetCode.NOT_LOGIN.getMsg());
                    httpServletResponse.setCharacterEncoding("UTF-8");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.getWriter().write(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue));
                    return false;
                }

                return true;
            } else {
                //返回未登录
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("code", RetCode.NOT_LOGIN.getCode());
                result.put("msg", RetCode.NOT_LOGIN.getMsg());
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.getWriter().write(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue));
                return false;
            }

        }
        else {


            //pc端
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            User user = (User) session.getAttribute(User.KEY);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            if (user == null) {
                ret.setCode(RetCode.NOT_LOGIN);
                response.getWriter().append(JSON.toJSONString(ret));
                return false;
            } else {
                return true;
            }

        }
    }
}

